<?php

namespace App\Filament\Resources\Admin\Users\Tables;

use App\Models\Admin\AdminUser;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Spatie\Permission\Models\Role;

class AdminUsersTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->striped()
            ->modifyQueryUsing(fn (Builder $query) => $query->with('roles')->orderByDesc('id'))
            ->columns(static::getTableColumns())
            ->filters([
                Filter::make('base')
                    ->schema([
                        TextInput::make('name')
                            ->label('姓名')
                            ->placeholder('请输入姓名'),
                        TextInput::make('email')
                            ->label('邮箱地址')
                            ->placeholder('请输入姓名'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query->when($data['name'], fn (Builder $query, $name): Builder => $query->where('name', $name))
                            ->when($data['email'], fn (Builder $query, $email): Builder => $query->where('email', $email));
                    })
                    ->indicateUsing(function (array $data): ?string {
                        if (! $data['name'] && ! $data['email']) {
                            return null;
                        }

                        return ($data['name'] ? '姓名：'.$data['name'].'，' : '').($data['email'] ? '邮箱：'.$data['email'] : '');
                    }),
            ])
            ->filtersTriggerAction(fn (Action $action) => $action->button()->label(''))
            ->columnManagerTriggerAction(fn (Action $action) => $action->button()->label(''))
            ->deferColumnManager(false)
            ->recordActions([
                static::getEditAction(),
                DeleteAction::make()
                    ->action(function (AdminUser $record) {
                        if ($record->is_super) {
                            Notification::make()
                                ->title('超级管理员不能删除')
                                ->danger()
                                ->send();

                            return;
                        }
                        $record->delete();
                        $record->roles()->delete();
                    })->visible(fn ($record) => auth()->user()->can('admin.user.delete') && $record->id !== 1),
            ])
            ->toolbarActions([
                    static::getCreateAction(),
            ]);
    }

    public static function getTableColumns(): array
    {
        $columns = [
            TextColumn::make('id')->sortable(),
            TextColumn::make('name')
                ->label('姓名'),
            TextColumn::make('email')
                ->copyable()
                ->copyMessage('复制成功')
                ->label('邮箱地址')
                ->copyMessageDuration(1500),
            TextColumn::make('roles.title')
                ->label('角色')
                ->bulleted()
                ->limitList()
                ->expandableLimitedList()
                ->listWithLineBreaks(),
        ];

        if (auth()->user()->can('admin.user.edit')) {
            $columns[] = ToggleColumn::make('status')
                ->label('状态');
        } else {
            $columns[] = TextColumn::make('status')
                ->label('状态')
                ->badge()
                ->formatStateUsing(fn ($state): string => match ($state) {
                    1 => '启用',
                    0 => '禁用'
                })
                ->color(fn ($record) => $record->status ? 'success' : 'danger');
        }

        $columns[] = TextColumn::make('created_at')
            ->label('创建时间');

        return $columns;
    }

    public static function getEditAction(): Action
    {
        return EditAction::make()
            ->label('编辑')
            ->modalHeading('编辑管理员')
            ->modalSubmitActionLabel('保存')
            ->modalCancelActionLabel('取消')
            ->schema(static::getForm(true))
            ->action(function (array $data, AdminUser $record): void {
                if (! $data['password']) {
                    unset($data['password']);
                }
                $record->update($data);
                if ($data['role_id']) {
                    $record->syncRoles(Role::whereIn('id', $data['role_id'])->pluck('name')->toArray());
                }
            })
            ->successNotificationTitle('账号修改成功')
            ->visible(fn () => auth()->user()->can('admin.user.edit'));
    }

    public static function getCreateAction(): Action
    {
        return CreateAction::make()
            ->label('创建管理员')
            ->modalHeading('添加管理员')
            ->modalSubmitActionLabel('保存')
            ->modalCancelActionLabel('取消')
            ->schema(static::getForm())
            ->createAnother(false)
            ->action(function (array $data): void {
                $user = AdminUser::create($data);
                if ($data['role_id']) {
                    $user->syncRoles(Role::whereIn('id', $data['role_id'])->pluck('name')->toArray());
                }
            })
            ->successNotificationTitle('账号创建成功')
            ->visible(fn () => auth()->user()->can('admin.user.add'));
    }

    public static function getForm(bool $isEdit = false): array
    {
        return [
            TextInput::make('name')
                ->label('姓名')
                ->placeholder('请输入管理员姓名')
                ->required()
                ->maxLength(255),
            TextInput::make('email')
                ->label('邮箱地址')
                ->placeholder('请输入邮箱地址')
                ->required()
                ->email()
                ->unique(AdminUser::class, 'email', ignoreRecord: true),
            TextInput::make('password')
                ->label('登录密码')
                ->placeholder('请输入登录密码')
                ->minLength(6)
                ->maxLength(16)
                ->password()
                ->required(! $isEdit),
            Select::make('role_id')
                ->label('角色')
                ->placeholder('请选择角色')
                ->native(false)
                ->multiple()
                ->options(fn () => Role::pluck('title', 'id'))
                ->loadStateFromRelationshipsUsing(function (callable $set, $record) {
                    if ($record) {
                        $set('role_id', $record->roles->pluck('id')->toArray());
                    }
                }),
            Toggle::make('status')
                ->label('状态'),
        ];
    }
}
